package com.jpcc.vw.onlineRadio.utils;

import android.content.Context;
/*Start by menglingqiang*/
import android.text.TextUtils;
import android.util.Log;
/*End by menglingqiang*/

import com.google.gson.Gson;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.jpcc.vw.onlineRadio.R;
import com.jpcc.vw.onlineRadio.application.MusicApplication;
import com.jpcc.vw.onlineRadio.constants.Constants;
import com.jpcc.vw.onlineRadio.db.DatabaseHelperOrm;
import com.jpcc.vw.onlineRadio.http.HttpClient;
import com.jpcc.vw.onlineRadio.model.IRadio;
import com.jpcc.vw.onlineRadio.model.bean.AddUserHistoryBean;
import com.jpcc.vw.onlineRadio.model.bean.BaseBean;
import com.jpcc.vw.onlineRadio.model.bean.PlayHistoryEntity;
import com.jpcc.vw.onlineRadio.model.bean.PlayHistoryOnlineBean;
import com.jpcc.vw.onlineRadio.model.bean.PlayHistoryOnlineEntity;
import com.jpcc.vw.onlineRadio.model.bean.RecentAlbumRadioTrackBean;
import com.jpcc.vw.onlineRadio.model.impl.RadioImpl;
/*Start by menglingqiang*/
import com.jpcc.vw.tracelog.TracelogInterface;
/*End by menglingqiang*/
import com.zhy.http.okhttp.callback.StringCallback;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/*Start by menglingqiang*/
import java.util.Date;
/*End by menglingqiang*/

import okhttp3.Call;

public class SyncHistoryUtils {

    public interface onSyncHistory {

        void onSyncHistorySuccess();

        void onsyncHistoryFail();
    }


    public static void syncHistory(Context context, onSyncHistory callback) {
        IRadio model = new RadioImpl();

        /*Start by menglingqiang*/
        Date dt = new Date();
        try {
            TracelogInterface inter = MusicApplication.getLogInterface();
            if(inter != null){
                inter.sendLogData(dt.toString(),dt.toString(),PlayHistoryOnlineBean.class.getName(),"DEBUG",null,"getPlayHistory request");
            }else {
                Log.e("JPCC","inter == null");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        /*End by menglingqiang*/

        model.getPlayHistory().subscribe(new CommonSubscriber<PlayHistoryOnlineBean>() {
            @Override
            public void onSuccess(PlayHistoryOnlineBean response) {
                DatabaseHelperOrm helper = DatabaseHelperOrm.getHelper(context);
                DeleteBuilder deleteBuilder = null;

                /*Start by menglingqiang*/
                Date dt = new Date();
                try {
                    TracelogInterface inter = MusicApplication.getLogInterface();
                    if(inter != null){
                        inter.sendLogData(dt.toString(),dt.toString(),PlayHistoryOnlineBean.class.getName(),"DEBUG",response.getStatusCode().toString(),"getPlayHistory onSuccess");
                    }else {
                        Log.e("JPCC","inter == null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                /*End by menglingqiang*/

                try {
                    if (response.getData() != null) {
                        deleteBuilder = helper.getRecentDao().deleteBuilder();
                        deleteBuilder.where().eq("userId", MusicApplication.GetUserId());
                        deleteBuilder.delete();
                        for (PlayHistoryOnlineEntity entityOnline : response.getData()) {
                            RecentAlbumRadioTrackBean localData=new RecentAlbumRadioTrackBean();
                            localData.setUserId(MusicApplication.GetUserId());
                            if(entityOnline.getContentType()==1){
                                localData.setType("album");
                            }
                            else{
                                localData.setType("radio");
                            }
                            if(entityOnline.getContentType()==1){
                                if(entityOnline.getAlbum()!=null&&entityOnline.getTrack()!=null){
                                    localData.setTrackId(entityOnline.getTrack().getId());
                                    localData.setTrackName(entityOnline.getTrack().getTitle());
                                    if(entityOnline.getTrack()!=null&&entityOnline.getTrack().getPlayInfo()!=null&&entityOnline.getTrack().getPlayInfo().getDownloadUrl()!=null){
                                        localData.setDownloadUrl(entityOnline.getTrack().getPlayInfo().getDownloadUrl().getUrl());
                                    }
                                    localData.setTrackUrl(entityOnline.getTrack().getPlayUrl32());
                                    localData.setDuration((int)entityOnline.getTrack().getDuration());
                                    localData.setCurrentDuration(entityOnline.getPlayedSecs()*1000);
                                    localData.setAlbumId(entityOnline.getAlbum().getId());
                                    localData.setCover(entityOnline.getAlbum().getCoverUrlLarge());
                                    localData.setAlbumName(entityOnline.getAlbum().getTitle());
                                    localData.setAuthor("");
                                    localData.setVipFree(entityOnline.getAlbum().isVipFree());
                                }

                            }
                            else{
                                if(entityOnline.getRadio()!=null&&entityOnline.getProgram()!=null){
                                    localData.setAlbumId(entityOnline.getRadio().getId());
                                    localData.setCover(entityOnline.getRadio().getLarge_cover_url());
                                    localData.setAlbumName(entityOnline.getRadio().getName());
                                    localData.setAuthor("");
                                    localData.setTrackId(entityOnline.getProgram().getId());
                                    if(!TextUtils.isEmpty(entityOnline.getProgram().getProgram_name())){
                                        localData.setTrackName(entityOnline.getProgram().getProgram_name());
                                    }
                                    else if(!TextUtils.isEmpty(entityOnline.getRadio().getPlaying_program_name())){
                                        localData.setTrackName(entityOnline.getRadio().getPlaying_program_name());
                                    }
                                    else{
                                        localData.setTrackName("");
                                    }
                                    localData.setLive(true);
                                }
                            }
                            localData.setFrom(4);
                            localData.setTimeStamp(entityOnline.getStartedAt());
                            helper.getRecentDao().create(localData);
                        }
                        if(callback!=null){
                            callback.onSyncHistorySuccess();
                        }
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(BaseBean response) {
                ToastUtils.show(R.string.string_117);

                /*Start by menglingqiang*/
                Date dt = new Date();
                try {
                    TracelogInterface inter = MusicApplication.getLogInterface();
                    if(inter != null){
                        inter.sendLogData(dt.toString(),dt.toString(),PlayHistoryOnlineBean.class.getName(),"ERROR",response.getStatusCode().toString(),"getPlayHistory onFailure");
                    }else {
                        Log.e("JPCC","inter == null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                /*End by menglingqiang*/


                if(callback!=null){
                    callback.onsyncHistoryFail();
                }
            }
        });
    }


    private static void mergeHistoryData(Context context, List<PlayHistoryEntity> datas, onSyncHistory callback, long lastSync) {
//        DatabaseHelperOrm helper = DatabaseHelperOrm.getHelper(context);
//        try {
//            List<RecentAlbumRadioTrackBean> recents = helper.getRecentDao().queryBuilder().orderBy("timeStamp", false).where().eq("userId", MusicApplication.GetUserId()).query();
//            List<PlayHistoryEntity> dataNeedSync = new ArrayList<>();
//            long lastSyncTime = 0;
//            if (datas == null || datas.size() == 0) {
//                lastSyncTime = 0;
//            } else {
//                lastSyncTime = lastSync;
//            }
//            for (RecentAlbumRadioTrackBean recent : recents) {
//                if (recent.getTimeStamp() > lastSync) {
//                    PlayHistoryEntity entity = new PlayHistoryEntity();
//                    if ("album".equals(recent.getType())) {
//                        entity.setContentType(1);
//                        entity.setAlbumId(recent.getAlbumId());
//                        entity.setTrackId(recent.getTrackId());
//                        entity.setAlbumTitle(recent.getAlbumName());
//                        entity.setTrackTitle(recent.getTrackName());
//                        entity.setPlayBeginAt(recent.getTimeStamp());
////                        entity.setBreakSecond(recent.getCurrentDuration() / 1000);
//                        entity.setTrackCoverUrlLarge(recent.getCover());
//                    } else {
//                        entity.setContentType(2);
//                        entity.setRadioId(recent.getAlbumId());
//                        entity.setScheduleId(-999);
//                        entity.setRadioName(recent.getAlbumName());
//                        entity.setProgramName("");
//                        entity.setPlayBeginAt(recent.getTimeStamp());
////                        entity.setBreakSecond(recent.getCurrentDuration() / 1000);
//                        entity.setRadioCoverUrlLarge(recent.getCover());
//                    }
//                    dataNeedSync.add(entity);
//                }
//            }
//            AddUserHistoryBean request = new AddUserHistoryBean();
//            request.setPlayHistoryRecords(dataNeedSync);
//            HttpClient.AddUserHistory(new Gson().toJson(request), new StringCallback() {
//                @Override
//                public void onError(Call call, Exception e, int id) {
//                    if (callback != null) {
//                        callback.onsyncHistoryFail();
//                    }
//                }
//
//                @Override
//                public void onResponse(String response, int id) {
//                    BaseBean result = new Gson().fromJson(response, BaseBean.class);
//                    if (result.getCode() == Constants.STATUS_SUCCESS_CODE) {
//                        if (callback != null) {
//                            callback.onSyncHistorySuccess();
//                        }
//                    } else {
//                        if (callback != null) {
//                            callback.onsyncHistoryFail();
//                        }
//                    }
//                }
//            });
//        } catch (SQLException e) {
//            e.printStackTrace();
//            if (callback != null) {
//                callback.onsyncHistoryFail();
//            }
//        }
    }

}
